/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.colswe.solestac.view;

import java.awt.Color;
import java.util.List;
import javax.swing.JOptionPane;
import org.colswe.solestac.control.AdministrationControl;
import org.colswe.solestac.entity.ActualUser;
import org.colswe.solestac.VO.RoleVO;
import org.colswe.solestac.VO.UserVO;

/**
 *
 * @author Julian Pena
 * @version 1.0
 */
public class ModifyUser extends javax.swing.JPanel {
    
    UserVO user;
    private long id;
    private String password;
    AdministrationControl ac = new AdministrationControl();
    /**
     * Creates new form NewUser
     */
    public ModifyUser() {
        initComponents();
        inicialize();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        cedulaTF = new javax.swing.JTextField();
        usuarioTF = new javax.swing.JTextField();
        rolCB = new javax.swing.JComboBox();
        reContrasenaTF = new javax.swing.JPasswordField();
        contrasenaTF = new javax.swing.JPasswordField();
        actualizarB = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        cambiarcontraCB = new javax.swing.JCheckBox();
        jLabel8 = new javax.swing.JLabel();
        viejaContrasenaTF = new javax.swing.JPasswordField();

        setBackground(new java.awt.Color(255, 255, 255));
        setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16));
        jLabel1.setText("Rol:");
        add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 280, 140, 20));

        jLabel3.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16));
        jLabel3.setText("Cedula:");
        add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 50, 160, 20));

        jLabel4.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16));
        jLabel4.setText("Nombre de Usuario:");
        add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 90, 160, 20));

        jLabel5.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16));
        jLabel5.setText("Contraseña:");
        add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 190, 110, 30));

        jLabel6.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16));
        jLabel6.setText("repetir contraseña:");
        add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 230, 160, 30));
        add(cedulaTF, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 40, 170, -1));
        add(usuarioTF, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 80, 170, -1));

        rolCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        add(rolCB, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 270, 230, -1));

        reContrasenaTF.setEnabled(false);
        add(reContrasenaTF, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 230, 170, -1));

        contrasenaTF.setEnabled(false);
        add(contrasenaTF, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 190, 170, -1));

        actualizarB.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16));
        actualizarB.setText("Actualizar");
        actualizarB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                actualizarBActionPerformed(evt);
            }
        });
        add(actualizarB, new org.netbeans.lib.awtextra.AbsoluteConstraints(470, 400, 130, 30));

        jLabel7.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16));
        jLabel7.setText("Cambiar Contraseña");
        add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 120, 180, 20));

        cambiarcontraCB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cambiarcontraCBActionPerformed(evt);
            }
        });
        add(cambiarcontraCB, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 120, -1, -1));

        jLabel8.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 16));
        jLabel8.setText("Contraseña vieja:");
        add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 160, 170, 20));

        viejaContrasenaTF.setEnabled(false);
        add(viejaContrasenaTF, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 150, 170, -1));
    }// </editor-fold>//GEN-END:initComponents

    private void actualizarBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_actualizarBActionPerformed
       
        CleanTF();
        boolean cambiarContra = false;
        if(cambiarcontraCB.isSelected()){
            String viejacontra = String.copyValueOf(viejaContrasenaTF.getPassword());
            String contra = String.copyValueOf(contrasenaTF.getPassword());
            String recontra = String.copyValueOf(reContrasenaTF.getPassword());
            
            List<UserVO> u = ac.searchByName(user.getUsername());
            UserVO x = u.get(0);
            if(!(x.getPassword().equals(viejacontra))){
                showWarningMssg("Contrasena vieja no coincide");
                return;
            }
            cambiarContra = true;
        }
        UserVO nuevo = new UserVO();
        nuevo.setDocument(cedulaTF.getText());
        nuevo.setUsername(usuarioTF.getText());
        nuevo.setId(id);
        nuevo.setPassword(password);
        nuevo.setRepassword(password);
        if(cambiarContra){
            nuevo.setPassword(String.copyValueOf(contrasenaTF.getPassword()));
            nuevo.setRepassword(String.copyValueOf(reContrasenaTF.getPassword()));
        }
        else{
            nuevo.setPassword(password);
        }
        nuevo.setRole((String)rolCB.getSelectedItem());
        int res = ac.updateUser(nuevo);
        
        if(res == 0){
            int confirm = JOptionPane.showConfirmDialog(null, "¿Está seguro que desea actualizar el usuario?", "¿Seguro?", 1, 2);
            if(confirm != 0){
                return;
            }
            showConfirmMssg("El usuario ha sido actualizado correctamente");            
            id = 0;
            password = null;
            cedulaTF.setText("");
            usuarioTF.setText("");
            cambiarcontraCB.setSelected(false);
            contrasenaTF.setText("");
            reContrasenaTF.setText("");
            viejaContrasenaTF.setText("");
            rolCB.setSelectedIndex(0);
            Principal principal = ActualUser.getInstance().getPrincipal();
            principal.userAdministration();
        }
        else if(res == -1){
            showWarningMssg("El nombre de usuario sólo puede tener número y letras");
            usuarioTF.setBackground(new Color(255,102,102));
            
        }
        else if(res == -2){
            showWarningMssg("El nombre de usuario debe tener entre 5 y 20 caracteres");
           usuarioTF.setBackground(new Color(255,102,102));
        }        
        else if(res == -3){
            showWarningMssg("La contrasena debe conterner al menos una letra Mayúscula, una minúscula y un número");
            contrasenaTF.setBackground(new Color(255,102,102));
        }
        else if(res == -4){
            showWarningMssg("La contrasena debe tener entre 5 y 30 caracteres");
            contrasenaTF.setBackground(new Color(255,102,102));
        }
        else if(res == -5){
            showWarningMssg("El nombre de usuario ya existe");
            usuarioTF.setBackground(new Color(255,102,102));
        }
        else if(res == -6){
            showWarningMssg("La contrasena y su confirmación no coinciden");
            reContrasenaTF.setBackground(new Color(255,102,102));
        }
        else if(res == -7){
            showWarningMssg("Cédula inválida");
            cedulaTF.setBackground(new Color(255,102,102));
        }
        else if(res == -8){            
            showWarningMssg("Ocurrió un problema inesperado");
        }
        else if(res == -9){
            showErrorMssg("Seleccione un rol por favor");
        }
        
    }//GEN-LAST:event_actualizarBActionPerformed

    private void showWarningMssg(final String Mssg){
        JOptionPane.showMessageDialog(this, Mssg, "Advertencia",JOptionPane.WARNING_MESSAGE);
    }
    
    private void showErrorMssg(final String Mssg){
        JOptionPane.showMessageDialog(this, Mssg, "Error", JOptionPane.ERROR_MESSAGE);
    }
    
     private void showConfirmMssg(final String Mssg){
        JOptionPane.showMessageDialog(this, Mssg);
    }
    
    private void CleanTF(){
        usuarioTF.setBackground(Color.white);
        contrasenaTF.setBackground(Color.white);
        reContrasenaTF.setBackground(Color.white);
        cedulaTF.setBackground(Color.white);
    }
    
    private void cambiarcontraCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cambiarcontraCBActionPerformed
        viejaContrasenaTF.setEnabled(cambiarcontraCB.isSelected());
        contrasenaTF.setEnabled(cambiarcontraCB.isSelected());
        reContrasenaTF.setEnabled(cambiarcontraCB.isSelected());
    }//GEN-LAST:event_cambiarcontraCBActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton actualizarB;
    private javax.swing.JCheckBox cambiarcontraCB;
    private javax.swing.JTextField cedulaTF;
    private javax.swing.JPasswordField contrasenaTF;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPasswordField reContrasenaTF;
    private javax.swing.JComboBox rolCB;
    private javax.swing.JTextField usuarioTF;
    private javax.swing.JPasswordField viejaContrasenaTF;
    // End of variables declaration//GEN-END:variables

    void user(UserVO uvo) {
        user = uvo;
        id = uvo.getId();
        password = (ac.searchByName(uvo.getUsername())).get(0).getPassword();
        cedulaTF.setText(String.valueOf(uvo.getDocument()));
        usuarioTF.setText(uvo.getUsername());
        rolCB.setSelectedItem(uvo.getRole());
    }

    private void inicialize() {
        rolCB.removeAllItems();
        rolCB.addItem("--Seleccione Rol--");
        List<RoleVO> roles = ac.getAllRoles();
        for(RoleVO rol: roles){
            rolCB.addItem(rol.getName());
        }
        CleanTF();
    }
}
